package cn.maiyar.web.xss.config;

import cn.maiyar.web.xss.XssProperties;
import cn.maiyar.web.xss.filter.XssFilter;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.DispatcherType;

/**
 * xss配置类
 *
 * @author c.c
 */
@Slf4j
@Configuration
@AllArgsConstructor
@ConditionalOnProperty(value = "meta.xss.enabled", havingValue = "true")
@EnableConfigurationProperties(XssProperties.class)
public class XssConfiguration implements WebMvcConfigurer {

    private final XssProperties xssProperties;

    /**
     * 防XSS注入
     */
    @Bean
    public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
        log.debug("初始化 XssConfiguration xssFilterRegistration!");
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter(xssProperties));
        registration.addUrlPatterns("/*");
        registration.setName("xssFilter");
        registration.setOrder(Ordered.LOWEST_PRECEDENCE);
        return registration;
    }
}
